<!-- 企业微信预约会议 -->
<template>
    <a-form layout="vertical" style="padding: 40px; overflow-y: auto">
      <!-- 会议主题 -->
      <a-form-item label="会议主题">
        <a-input v-model="formData.subject" placeholder="请输入会议主题" />
      </a-form-item>

      <!-- 会议开始时间 -->
      <a-form-item label="开始时间">
        <a-date-picker
          v-model="formData.startTime"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          :time-picker-props="{
            format: 'HH:mm',
            hideDisabledOptions: true,
            disabledHours: [],
          }"
          :disabled-time="disabledTime"
          @change="onStartTimeChange"
        />
      </a-form-item>

      <!-- 持续时间 -->
      <a-form-item label="持续时间（分钟）">
        <a-input-number v-model="formData.length" :min="1" />
      </a-form-item>
      <!-- 是否开启周期会议 -->
      <a-form-item>
        <a-checkbox v-model="isRecurringMeeting" @change="toggleRecurringMeeting">
          启用周期会议
        </a-checkbox>
      </a-form-item>

      <div v-if="isRecurringMeeting">
        <a-form-item label="循环开始日期">
          <a-date-picker v-model="cycleParams.startDate" format="YYYY-MM-DD" />
        </a-form-item>

        <a-form-item label="循环结束日期">
          <a-date-picker v-model="cycleParams.endDate" format="YYYY-MM-DD" />
        </a-form-item>

        <a-form-item label="循环类型">
          <a-select
            v-model="cycleParams.cycle"
            placeholder="请选择循环类型"
            @change="onCycleChange"
          >
            <a-option value="Day">日</a-option>
            <a-option value="Week">周</a-option>
            <a-option value="Month">月</a-option>
          </a-select>
        </a-form-item>

        <a-form-item label="间隔周期(日：每隔几日  周：每隔几周  月：每隔几月)">
          <a-input-number v-model="cycleParams.interval" :min="1" />
        </a-form-item>

        <template v-if="cycleParams.cycle === 'Week'">
          <a-form-item label="每周选择">
            <a-checkbox-group v-model="cycleParams.point">
              <a-checkbox value="1">星期一</a-checkbox>
              <a-checkbox value="2">星期二</a-checkbox>
              <a-checkbox value="3">星期三</a-checkbox>
              <a-checkbox value="4">星期四</a-checkbox>
              <a-checkbox value="5">星期五</a-checkbox>
              <a-checkbox value="6">星期六</a-checkbox>
              <a-checkbox value="0">星期天</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
        </template>

        <template v-if="cycleParams.cycle === 'Month'">
          <a-form-item label="每月选择">
            <a-checkbox-group v-model="cycleParams.point">
              <a-checkbox value="1">1号</a-checkbox>
              <a-checkbox value="2">2号</a-checkbox>
              <a-checkbox value="3">3号</a-checkbox>
              <a-checkbox value="4">4号</a-checkbox>
              <a-checkbox value="5">5号</a-checkbox>
              <a-checkbox value="6">6号</a-checkbox>
              <a-checkbox value="7">7号</a-checkbox>
              <a-checkbox value="8">8号</a-checkbox>
              <a-checkbox value="9">9号</a-checkbox>
              <a-checkbox value="10">10号</a-checkbox>
              <a-checkbox value="11">11号</a-checkbox>
              <a-checkbox value="12">12号</a-checkbox>
              <a-checkbox value="13">13号</a-checkbox>
              <a-checkbox value="14">14号</a-checkbox>
              <a-checkbox value="15">15号</a-checkbox>
              <a-checkbox value="16">16号</a-checkbox>
              <a-checkbox value="17">17号</a-checkbox>
              <a-checkbox value="18">18号</a-checkbox>
              <a-checkbox value="19">19号</a-checkbox>
              <a-checkbox value="20">20号</a-checkbox>
              <a-checkbox value="21">21号</a-checkbox>
              <a-checkbox value="22">22号</a-checkbox>
              <a-checkbox value="23">23号</a-checkbox>
              <a-checkbox value="24">24号</a-checkbox>
              <a-checkbox value="25">25号</a-checkbox>
              <a-checkbox value="26">26号</a-checkbox>
              <a-checkbox value="27">27号</a-checkbox>
              <a-checkbox value="28">28号</a-checkbox>
              <a-checkbox value="29">29号</a-checkbox>
              <a-checkbox value="30">30号</a-checkbox>
              <a-checkbox value="31">31号</a-checkbox>
            </a-checkbox-group>
            <span v-if="invalidDateWarning" style="color: red"
              >请注意，某些日期在二月份可能不存在。</span
            >
          </a-form-item>
        </template>
      </div>
      <!-- <template #custom-left> -->

      <!-- 会议类型 -->
      <a-form-item label="会议类型">
        <a-select
          v-model="formData.meetType"
          placeholder="请选择会议类型"
          allow-clear
          @change="handleMeetingTypeChange"
        >
          <a-option :value="0">线下</a-option>
          <a-option :value="1">线上</a-option>
        </a-select>
      </a-form-item>
      <!-- 只有在会议类型为线下时才显示厂区、办公楼和会议室选择 -->
      <a-form-item v-if="formData.meetType === 0" label="厂区">
        <a-select
          v-model="selectedFactoryId"
          placeholder="请选择厂区"
          @change="onFactoryChange"
        >
          <a-option
            v-for="factory in factoryList"
            :key="factory.id"
            :value="factory.id"
          >
            {{ factory.name }}
          </a-option>
        </a-select>
      </a-form-item>
      <!-- 只有在会议类型为线下时才显示厂区、办公楼和会议室选择 -->
      <!-- 选择办公楼，显示按钮 -->
      <a-form-item
        v-if="formData.meetType === 0 && selectedFactoryId"
        label="办公楼"
      >
        <a-select
          v-model="selectedBuildingId"
          placeholder="请选择办公楼"
          @change="onBuildingChange"
        >
          <a-option
            v-for="building in buildingList"
            :key="building.id"
            :value="building.id"
          >
            {{ building.name }}
          </a-option>
        </a-select>
        <a-button
          v-if="selectedBuildingId"
          type="primary"
          style="margin-top: 10px"
          @click="openRoomStatusModal"
        >
          查看会议室占用情况
        </a-button>
      </a-form-item>

      <a-form-item
        v-if="formData.meetType === 0 && selectedBuildingId"
        label="会议室"
      >
        <a-select v-model="formData.meetRoomId" placeholder="请选择会议室">
          <a-option
            v-for="room in meetingRoomList"
            :key="room.id"
            :value="room.id"
          >
            <template #default>
              <div class="meeting-room-option">
                <img
                  :src="room.imageUrl"
                  alt="会议室图片"
                  class="room-image"
                  @click.stop="openImageModal(room.imageUrl)"
                />
                <span
                  >{{ room.name }} ({{ room.floor }}, 容纳
                  {{ room.capacity }} 人)</span
                >
              </div>
            </template>
          </a-option>
        </a-select>
      </a-form-item>

      <!-- 媒体类型选择器 -->
      <a-form-item label="媒体类型">
        <a-select
          v-model="formData.mediaTypes"
          placeholder="请选择媒体类型"
          allow-clear
        >
          <a-option value="Voice">音频</a-option>
          <a-option value="Video">视频</a-option>
        </a-select>
      </a-form-item>
      <!-- 来宾设置 -->
      <!-- 来宾设置 -->
      <a-form-item label="来宾设置" class="form-item">
        <div class="guest-settings">
          <!-- 是否免密的复选框 -->
          <a-checkbox
            v-model="formData.confConfigInfo.isGuestFreePwd"
            class="form-checkbox"
          >
            关闭来宾密码
          </a-checkbox>

          <!-- 如果免密，显示来宾密码输入框 -->
          <a-input
            v-if="!formData.confConfigInfo.isGuestFreePwd"
            v-model="formData.confConfigInfo.guestPwd"
            placeholder="请输入来宾密码"
            class="form-input"
          />

          <!-- 限制范围文字 -->
          <div class="restriction-label">限制范围</div>

          <!-- 呼入限制选择 -->
          <a-select
            v-model="formData.confConfigInfo.callInRestriction"
            placeholder="请选择加入限制"
            class="full-width"
          >
            <a-option :value="0">无限制</a-option>
            <a-option :value="1">仅限内部用户</a-option>
          </a-select>

          <!-- 是否开启等候室 -->
          <a-checkbox
            v-model="formData.confConfigInfo.enableWaitingRoom"
            class="form-checkbox"
          >
            开启等候室
          </a-checkbox>
        </div>
      </a-form-item>
      <a-form-item label="与会人" class="invite-container">
        <div>
          <div class="invite-header">
            <a-button type="primary" @click="showInviteModal = true"
              >
邀请与会人
</a-button
            >
</div>

          <div v-if="selectedUsers.length > 0" class="selected-users">
            <div
              v-for="(user, index) in selectedUsers"
              :key="user.userid"
              class="user-card"
              @mouseover="hoverIndex = index"
              @mouseleave="hoverIndex = -1"
            >
              <img
                :src="user.avatar || 'https://via.placeholder.com/30'"
                class="user-avatar"
              />
              <span class="user-name">{{ user.name }}</span>

              <!-- X 按钮 -->
              <span
                v-if="hoverIndex === index"
                class="delete-btn"
                @click="removeUser(index)"
                >✖</span
              >
            </div>
          </div>
          <div style="padding: 20px 0px;">
              <a-form-item label="预约人" class="invite-container">
                  <a-tree-select
              v-model="treeUser"
      :data="userTreeDataReservation"
      placeholder="请选择预约人"
      style="width: 300px"
      @change="treeUserChange()"
    ></a-tree-select>
              </a-form-item>
</div>
        </div>
      </a-form-item>
      <div
        class="invite-header"
        style="margin-left: auto; padding: 0px 100px 0px 0px"
      >
        <a-popconfirm content="确认提交吗?" @ok="onScheduleMeetingSubmit">
          <a-button type="primary">提交</a-button>
        </a-popconfirm>
      </div>
    </a-form>

    <a-modal
      v-model:visible="showInviteModal"
      title="邀请与会人"
      @ok="handleInviteConfirm"
    >
      <a-tree
        v-model:checked-keys="checkedUserIds"
        checkable
        :data="userTreeData"
      />
    </a-modal>
  </template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { computed, ref, watch } from 'vue'
import { debounce } from 'lodash-es'
import { Message } from '@arco-design/web-vue'
import { useRoute } from 'vue-router'
import type { IMeeting } from './type'
import {
  escMeeting,
  getAvailableRooms,
  getBuildingList,
  getFactoryList,
  getMeetingList,
  getRoomStatus,
  getUserTree,
  scheduleMeeting
} from '@/apis/startApp/meeting'
import { useDevice, useForm } from '@/hooks'
// 获取用户树

defineOptions({ name: 'StartApp' })
// 控制邀请弹窗
const showInviteModal = ref(false)
// 控制预约会议弹窗
const showScheduleMeetingModal = ref(false)
const hoverIndex = ref(-1) // 记录鼠标悬停的索引
const treeUser = ref() // 预约人的树选择值
// 选择的厂区和办公楼
const selectedFactoryId = ref<number | null>(null)
const selectedBuildingId = ref<number | null>(null)
const selectedRoomId = ref<number | null>(null)
const infoBoxPosition = ref({ x: 0, y: 0 })
const showInfoBox = ref(false)
const currentInfo = ref({
  initiator: '',
  phone: '',
  department: '',
  start: '',
  end: ''
})
// 存储树形结构数据
const userTreeData = ref([])
const userTreeDataReservation = ref([])
// 已选中的 `userid`（最终返回）
const selectedUsers = ref<{ userid: string, name: string, avatar: string }[]>(
  []
)

// 绑定到 `a-tree` 组件的 `checkedUserIds`
const checkedUserIds = ref<string[]>([])
const selectUserIds = ref<string[]>([])
const meetingRoomList = ref<
  {
    id: number
    name: string
    floor: string
    capacity: number
    imageUrl: string
  }[]
>([])

const route = useRoute()
let userId
    = route.params.userId?.toString() || route.query.userId?.toString() || null
const meetingLoading = ref(false)
const meetingList = ref<IMeeting[]>([])
const noDataState = ref(false)
// 厂区数据
const factoryList = ref<{ id: number, name: string }[]>([])
const buildingList = ref<{ id: number, name: string }[]>([])
const showImageModal = ref(false) // 控制大图模态框的显示
const selectedImage = ref('') // 存储选择的图片 URL
const roomStatus = ref([]) // 用于存储会议室状态数据
const showRoomStatusModal = ref(false)
// 是否启用周期会议
const isRecurringMeeting = ref(false)
// 周期会议参数
// 周期会议参数状态
// 周期会议参数状态
const cycleParams = ref({
  startDate: null,
  endDate: null,
  cycle: '',
  interval: 1,
  point: [] // 周期点
})

// 用于标识是否存在无效日期的警告
const invalidDateWarning = ref(false)
// 选中的日期状态
const selectedDate = ref(dayjs().format('YYYY-MM-DD'))

// 格式化后的日期，用于显示
const formattedDate = computed(() =>
  dayjs(selectedDate.value).format('M月D日 dddd')
)
// 打开图片模态框
const openImageModal = (imageUrl) => {
  selectedImage.value = imageUrl // 设置要显示的大图 URL
  showImageModal.value = true // 显示模态框
}
/**
 * 选择预约人
 */
const treeUserChange = () => {
  userId = treeUser.value
  console.log(userId)
}
/**
 * 取消会议事件
 * @param e 会议信息
 */
const EscMeeting = async (e: any) => {
  // 取消会议
  const res = await escMeeting(e.conferenceId)
  if (res.data.success === true) {
    Message.success('会议取消成功')
    // 重新查询会议列表
    fatchMeetingList()
  } else {
    Message.success('会议取消失败')
  }
}
/**
 * 复制链接按钮功能
 * @param e 会议信息
 */
const copyLink = async (e: any) => {
  if (e.meetUrl) {
    try {
      // 复制链接
      await navigator.clipboard.writeText(e.meetUrl)
      Message.success('复制成功')
    } catch (err) {
      console.log(err)
    }
  }
}

// 辅助函数：根据 key 找到节点
// 筛选仅用户节点
function onCheck(checkedKeys) {
  const filteredKeys = checkedKeys.filter((key) => {
    const node = findNodeByKey(userTreeData, key)
    return node && node.type !== 'department' // 排除部门节点
  })
  checkedUserIds.value = filteredKeys
  selectUserIds.value = filteredKeys
}

// 辅助函数：查找节点
function findNodeByKey(treeData, key) {
  for (const node of treeData) {
    if (node.key === key) {
      return node
    }
    if (node.children) {
      const found = findNodeByKey(node.children, key)
      if (found) {
        return found
      }
    }
  }
  return null
}
const fetchRoomStatus = async (date) => {
  try {
    const response = await getRoomStatus(selectedBuildingId.value)
    // 只保留与选定日期相关的占用时期
    const filteredData = response.map((room) => {
      const filteredPeriods = room.occupancyPeriods.filter((period) => {
        return dayjs(period.start).isSame(date, 'day')
      })
      return { ...room, occupancyPeriods: filteredPeriods }
    })
    roomStatus.value = filteredData
  } catch (error) {
    console.error('获取会议室状态失败:', error)
  }
}
watch(selectedDate, (newDate) => {
  fetchRoomStatus(newDate)
})
const closeRoomStatusModal = () => {
  showRoomStatusModal.value = false
}

// 在办公楼变化时调用此方法
watch(selectedBuildingId, (newBuildingId) => {
  if (newBuildingId) {
    fetchRoomStatus(newBuildingId)
  }
})
// 关闭图片模态框
const closeImageModal = () => {
  showImageModal.value = false // 隐藏模态框
}
const showInfo = (periods, slot, event) => {
  const info = periods.find(({ start, end }) => {
    const startOfDay = dayjs(selectedDate.value).startOf('day')
    const slotStart = startOfDay.add((slot - 1) * 15, 'minute')
    return (
      dayjs(start).isBefore(slotStart.add(15, 'minute'))
      && dayjs(end).isAfter(slotStart)
    )
  })

  if (info) {
    currentInfo.value = {
      initiator: info.initiator,
      phone: info.phone,
      department: info.department,
      start: dayjs(info.start).format('HH:mm'),
      end: dayjs(info.end).format('HH:mm')
    }
    // 设置位置为鼠标点击处的右下角偏移
    infoBoxPosition.value = { x: event.clientX + 10, y: event.clientY + 10 }
    showInfoBox.value = true
  }
}

const closeInfoBox = () => {
  showInfoBox.value = false
}
const removeUser = (index: number) => {
  const removedUserId = selectedUsers.value[index].userid

  // 1️⃣ 从 `selectedUsers` 里删除该用户
  selectedUsers.value.splice(index, 1)

  // 2️⃣ 同步更新 `a-tree` 组件的 `checkedUserIds`
  checkedUserIds.value = checkedUserIds.value.filter(
    (id) => id !== removedUserId
  )

  selectUserIds.value = selectUserIds.value.filter((id) => id !== removedUserId)
}

// 处理周期类型变化
// 处理周期类型的变化
// 处理周期类型的变化
const onCycleChange = (value) => {
  cycleParams.value.cycle = value

  if (value === 'Day') {
    cycleParams.value.point = [] // 清空周期点
  } else if (value === 'Week') {
    cycleParams.value.point = [] // 重新设置为数组，以便用户选择周几
  } else if (value === 'Month') {
    cycleParams.value.point = null // 清掉 `point`
  }
}

const openRoomStatusModal = async () => {
  await fetchRoomStatus(selectedDate.value)
  showRoomStatusModal.value = true
}
// 设置为今天的日期
const goToToday = () => {
  selectedDate.value = dayjs().format('YYYY-MM-DD')
}

// 前一天
const prevDay = () => {
  selectedDate.value = dayjs(selectedDate.value)
    .subtract(1, 'day')
    .format('YYYY-MM-DD')
}

// 后一天
const nextDay = () => {
  selectedDate.value = dayjs(selectedDate.value)
    .add(1, 'day')
    .format('YYYY-MM-DD')
}
// 会议表单数据
const formData = ref({
  subject: '',
  startTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  length: 45,
  mediaTypes: '', // ✅ 默认 `HDVideo`
  meetRoomId: undefined, // ✅ 线下会议时必填
  meetType: 1, // 1=线上会议, 0=线下会议

  // ✅ 会议配置信息
  confConfigInfo: {
    isGuestFreePwd: false,
    callInRestriction: 0,
    guestPwd: '',
    enableWaitingRoom: false
  },

  // 可选的循环会议参数
  cycleParams: {
    startDate: null,
    endDate: null,
    cycle: '',
    interval: 1, // 默认间隔为1
    point: [] // 选择的周期点
  }
})

// 切换周期会议状态
const toggleRecurringMeeting = () => {
  if (!isRecurringMeeting.value) {
    // 如果取消勾选，重置周期参数
    cycleParams.value = {
      startDate: null,
      endDate: null,
      cycle: '',
      interval: 1,
      point: []
    }
  }
}
watch(
  selectedUsers,
  (newUsers) => {
    checkedUserIds.value = newUsers.map((user) => user.userid)
  },
  { deep: true }
)

// 打开预约会议弹窗
const openScheduleMeetingModal = async () => {
  showScheduleMeetingModal.value = true
  if (factoryList.value.length === 0) {
    // factoryList.value = await getFactoryList()
    factoryList.value = [
      { value: 1, label: '线上会议' }, // `1` 代表线上会议
      { value: 0, label: '线下会议' } // `0` 代表线下会议
    ]
  }
}

// 自定义时间禁用设置，使分钟只能选择每15分钟的时间
const disabledTime = () => {
  return {
    disabledHours: () => [],
    disabledMinutes: (hour) => {
      // 禁用非15的倍数的分钟
      return Array.from({ length: 60 }, (_, i) =>
        i % 15 !== 0 ? i : null).filter((i) => i !== null)
    }
  }
}

const isOccupied = (periods, slot, selectedDate) => {
  const startOfDay = dayjs(selectedDate).startOf('day')
  const slotStart = startOfDay.add((slot - 1) * 15, 'minute')
  const slotEnd = slotStart.add(15, 'minute') // 确保每个槽的结束时间正确

  return periods.some(({ start, end }) => {
    const periodStart = dayjs(start)
    const periodEnd = dayjs(end)
    return periodStart.isBefore(slotEnd) && periodEnd.isAfter(slotStart)
  })
}
const handleMeetingTypeChange = () => {
  if (formData.value.meetType === 1) {
    // 如果会议类型为线上，则清空线下相关选项
    selectedFactoryId.value = null
    selectedBuildingId.value = null
    formData.value.meetRoomId = 0 // 清空会议室选择
  }
}
// 获取厂区数据
const fetchFactories = async () => {
  try {
    factoryList.value = await getFactoryList()
  } catch (error) {
    console.error('获取厂区失败:', error)
  }
}

// 当厂区变化时，获取办公楼数据
const onFactoryChange = async () => {
  console.log('选中的厂区 ID:', selectedFactoryId.value)
  selectedBuildingId.value = null // 切换厂区时清空办公楼
  if (selectedFactoryId.value) {
    try {
      buildingList.value = await getBuildingList(selectedFactoryId.value)
      console.log('获取到的办公楼列表:', buildingList.value)
    } catch (error) {
      console.error('获取办公楼失败:', error)
    }
  }
}

const onBuildingChange = async () => {
  if (selectedBuildingId.value) {
    try {
      meetingRoomList.value = await getAvailableRooms(
        formData.value.startTime,
        formData.value.length,
        selectedBuildingId.value
      )
    } catch (error) {
      console.error('获取会议室失败:', error)
    }
  }
}
// 在表单中的开始时间和持续时间变化时，执行相关逻辑
watch(
  () => [formData.value.startTime, formData.value.length],
  ([newStartTime, newLength], [oldStartTime, oldLength]) => {
    if (
      formData.value.meetType === 0
      && (newStartTime !== oldStartTime || newLength !== oldLength)
    ) {
      onBuildingChange()
    }
  }
)
// 验证日期是否在二月份有效
// 验证日期是否在二月份有效
const validateDayForFebruary = (day) => {
  // 仅在选择了有效的开始日期后进行逻辑处理
  if (cycleParams.value.startDate) {
    const selectedMonth = new Date(cycleParams.value.startDate).getMonth() + 1 // 月份从0开始，所以需要加1

    // 检查是否为二月并且天数大于28
    if (selectedMonth === 2 && day > 28) {
      invalidDateWarning.value = true
    } else {
      invalidDateWarning.value = false // 日期有效
    }
  }
}
// 组件初始化时获取厂区数据
fetchFactories()
watch(
  () => formData.value.meetType,
  (newValue) => {
    console.log('会议类型变更:', newValue)
    console.log('会议类型变更:', formData.value.meetType)
  }
)
// 关闭预约会议弹窗
// 转换数据格式（确保 `userid` 绑定正确）
const transformTreeData = (data: any[]) => {
  return data.map((node) => ({
    title: node.name,
    key: node.type === 'user' ? node.userid : node.id?.toString(), // ✅ 用户用 userid，部门用 id
    value: node.type === 'user' ? node.userid : node.id?.toString(), // ✅ 用户用 userid，部门用 id
    selectable: node.type === 'user', // ✅ 只能选用户
    children:
        node.children && node.children.length > 0
          ? transformTreeData(node.children)
          : [],
    avatar: node.avatar || null // ✅ 头像
  }))
}
// 递归查找用户节点（根据 userid）
const findUserById = (tree, userid) => {
  for (const node of tree) {
    if (node.value === userid) return node
    if (node.children) {
      const found = findUserById(node.children, userid)
      if (found) return found
    }
  }
  return null
}

// 监听用户选择，点击 "确定" 时存入 `selectedUsers`
const handleInviteConfirm = () => {
  selectedUsers.value = checkedUserIds.value
    .map((userid) => {
      const userNode = findUserById(userTreeData.value, userid)
      return userNode
        ? { userid, name: userNode.title, avatar: userNode.avatar || '' }
        : null
    })
    .filter(Boolean)

  showInviteModal.value = false // ✅ 关闭弹窗
}

// 获取用户树数据
// 获取用户树数据
const fetchUserTree = async () => {
  try {
    const rawData = await getUserTree()
    userTreeData.value = transformTreeData(rawData)
    userTreeDataReservation.value = transformTreeData(rawData)
    console.log(rawData)

    // 确保在获取用户树后再添加用户信息
    // if (userId) {
    //   const userNode = findUserById(userTreeData.value, userId);
    //   if (userNode) {
    //     selectedUsers.value.push({
    //       userid: userId,
    //       name: userNode.title || "当前用户",
    //       avatar: userNode.avatar || "",
    //     });
    //   }
    // }
  } catch (error) {
    console.error('获取用户树失败:', error)
  }
}
const { isMobile, isDesktop } = useDevice()

const options: Options = {
  form: {
    rules: {
      keyword: [{ required: false, message: '' }]
    }
  },
  btns: { hide: true }
}
const { form } = useForm({
  keyword: ''
})
const columns = computed<Columns<typeof form>>(() => [
  {
    label: '',
    field: 'keyword',
    type: 'input',
    placeholder: '会议名称搜索',
    hide: false,
    span: 24
  }
])
/**
 * 获取会议列表
 */
const fatchMeetingList = debounce(() => {
  const params = { userId, ...form }
  meetingLoading.value = true
  getMeetingList(params)
    .then((res) => {
      meetingList.value = res.data
      noDataState.value = res.data.length == 0
      meetingLoading.value = false
    })
    .catch((_err) => {
      noDataState.value = true
      meetingLoading.value = false
    })
}, 500)

watch(form, (_newValue, _oldValue) => {
  fatchMeetingList()
})

const getDateValue = (value) => {
  const today = dayjs()
  const todayStr = today.format('YYYY-MM-DD')
  const tomorrow = today.add(1, 'day').format('YYYY-MM-DD')
  const dateStr = dayjs(value).format('YYYY-MM-DD')
  if (todayStr == dateStr) {
    return '今天'
  } else if (tomorrow == dateStr) {
    return '明天'
  } else {
    if (isMobile.value) {
      return dayjs(value).format('YYYY<br/>MM/DD')
    } else if (isDesktop.value) {
      return value
    }
  }
}
document.addEventListener(
  'touchmove',
  (e) => {
    e.passive = true
  },
  { capture: false, passive: true }
)
watch(selectedDate, (newDate) => {
  fetchRoomStatus(newDate)
})
const onStartTimeChange = (timeString) => {
  // 将时间字符串转换为dayjs对象
  const dateTime = dayjs(formData.value.startTime)
  // 更新开始时间，将秒数设置为00
  formData.value.startTime = dateTime
    .set('hour', dayjs(timeString).hour())
    .set('minute', dayjs(timeString).minute())
    .set('second', 0)
    .format('YYYY-MM-DD HH:mm:ss')
}
const getConferenceState = (value) => {
  switch (value) {
    case 0:
      return '待开始'
    case 1:
      return '正在开始'
    case 3:
      return '已结束'
    default:
      break
  }
}

const getParticipantStr = (participants) => {
  return participants
    .map((item) => {
      return item.realname
    })
    .join(', ')
}

const getTime = (time) => {
  return dayjs(time).format('HH:mm:ss')
}

const toUrl = (url) => {
  window.open(url)
}
const disabledDate = (current) => {
  // 可以根据需要禁用特定日期
  return current && current < dayjs().endOf('day') // 禁用今天之前的日期
}
const onStartApp = () => {
  window.location.href = 'http://1.94.243.106:5173/appawake.html'
}
// 重置表单函数
// 重置表单函数
const resetForm = () => {
  formData.value = {
    subject: '',
    startTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    length: 45,
    mediaTypes: '',
    meetRoomId: undefined,
    meetType: 1,
    confConfigInfo: {
      isGuestFreePwd: false,
      callInRestriction: 0,
      guestPwd: '',
      enableWaitingRoom: false
    },
    cycleParams: {
      startDate: null,
      endDate: null,
      cycle: '',
      interval: 1,
      point: []
    } // 重置循环会议参数
  }
  selectedFactoryId.value = null
  selectedBuildingId.value = null
  selectedUsers.value = []
  checkedUserIds.value = []
  isRecurringMeeting.value = false // 重置周期会议状态
  treeUser.value = null
}
// 提交预约会议
const onScheduleMeetingSubmit = async () => {
  if (!selectedUsers.value.length) {
    return Message.error('请选择与会者！')
  }

  if (!formData.value.subject) {
    return Message.error('请输入会议主题！')
  }

  if (!formData.value.startTime) {
    return Message.error('请选择会议开始时间！')
  }
  if (formData.value.meetType === 0 && !formData.value.meetRoomId) {
    return Message.error('请选择会议室！')
  }
  if (!formData.value.length) {
    return Message.error('请输入会议持续时间！')
  }

  if (!userId) {
    return Message.error('用户 ID 不能为空！')
  }
  const requestData = {
    userId, // ✅ 取自 URL
    subject: formData.value.subject,
    startTime: formData.value.startTime,
    length: formData.value.length,
    mediaTypes: formData.value.mediaTypes || 'HDVideo', // ✅ 默认 `HDVideo`
    meetRoomId: formData.value.meetRoomId,
    meetType: formData.value.meetType,

    // ✅ 会议配置信息
    confConfigInfo: {
      isGuestFreePwd: formData.value.confConfigInfo?.isGuestFreePwd || false,
      callInRestriction: formData.value.confConfigInfo?.callInRestriction || 0,
      guestPwd: formData.value.confConfigInfo?.guestPwd || '',
      enableWaitingRoom:
          formData.value.confConfigInfo?.enableWaitingRoom || false
    },

    // ✅ 如果是循环会议才提交 `cycleParams`
    cycleParams: isRecurringMeeting.value
      ? {
          startDate: cycleParams.value.startDate,
          endDate: cycleParams.value.endDate,
          cycle: cycleParams.value.cycle,
          interval: cycleParams.value.interval,
          point: cycleParams.value.point
        }
      : undefined,

    // ✅ 与会者列表
    attendees: selectedUsers.value.map((user) => ({
      accountId: user.userid,
      appId: '9dbd6b334e744eada42b45b3bf6b8402'
    }))
  }

  console.log('提交预约会议请求:', requestData)

  try {
    await scheduleMeeting(requestData)
    Message.success('会议预约成功！')
    // 成功后调用重置函数
    resetForm()
    fetchUserTree()
    showScheduleMeetingModal.value = false
    // 调用 fetchMeetingList 重新获取会议列表
    await fatchMeetingList()
  } catch (error) {
    Message.error('预约会议失败，请重试！')
    console.error('预约会议失败:', error)
  }
}

// 处理表单的关闭
const closeScheduleMeetingModal = () => {
  resetForm()
  fetchUserTree()
  showScheduleMeetingModal.value = false
}
onMounted(() => {
  //   fatchMeetingList();
})
onMounted(() => {
  fetchUserTree()
  selectedDate.value = dayjs().format('YYYY-MM-DD') // 初始化当天的日期
  if (selectedBuildingId.value) {
    fetchRoomStatus(selectedDate.value)
  }
})
</script>

    <style lang="scss" scoped>
  .name-box,
  .date,
  .promoter,
  .participant {
    padding-bottom: 10px;
  }

  .form-checkbox {
    margin-top: 20px;
    /* 调整上方间距 */
    margin-bottom: 20px;
    /* 调整下方间距 */
  }

  /* 为会议室图片和选项调整样式 */
  .meeting-room-option {
    display: flex;
    align-items: center;

    .room-image {
      width: 40px;
      height: 40px;
      object-fit: cover;
      border-radius: 4px;
      margin-right: 10px;
    }

    span {
      font-size: 14px;
      line-height: 1.2;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .large-image {
    width: 100%;
    /* 设置大图宽度适应模态框 */
    height: auto;
    /* 自动调整高度以保持比例 */
  }

  .room-image {
    width: 50px;
    /* 设置图片宽度，可以根据需要调整 */
    height: 50px;
    /* 设置图片高度，可以根据需要调整 */
    object-fit: cover;
    /* 保持图片比例并裁剪 */
    border-radius: 4px;
    /* 设置圆角 */
    flex-shrink: 0;
    /* 防止图片被压缩 */
  }

  .name-box {
    display: flex;
    justify-content: space-between;

    .name {
      font-weight: bold;
      flex: 1;
    }

    .status {
      font-weight: bold;
    }

    .status-0 {
      color: #ec7f39;
    }

    .status-1 {
      color: #008000;
    }

    .status-3 {
      color: #ff0000;
    }
  }

  .promoter,
  .participant {
    color: #6c676b;
    font-size: 13px;
  }

  .occupancy-slot.occupied {
    background-color: #90caf9;
  }

  .noData {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .arco-spin {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
  }

  .pc {
    display: flex;
    height: 100vh;

    .container-l {
      background-color: #f7f7f7;
      width: 200px;
      height: 100%;
      box-sizing: border-box;
      padding: 20px;

      .btn {
        width: 100%;
      }
    }

    .container-r {
      background-color: #ffffff;
      flex: 1;
      height: 100%;
      box-sizing: border-box;
      padding: 0 20px;
      display: flex;
      flex-direction: column;

      .search-query {
        margin-top: 20px;
      }

      .meeting-list {
        flex: 1;
        overflow-y: scroll;

        .title {
          color: #878986;
          padding: 15px 0;
          border-bottom: 2px solid #f6f6f6;
          font-weight: bold;
        }

        .meeting-item {
          padding: 15px 0;
          border-bottom: 2px solid #f9f9f9;

          .status {
            margin-right: 15px;
          }
        }
      }
    }
  }

  /* 预约会议按钮 */
  .btn {
    width: 100%;
    margin-top: 35px;
  }

  .h5 {
    font-size: 17px;
    background-color: #ffffff;
    height: 100vh;
    padding: 10px;
    box-sizing: border-box;

    .container {
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      /* 确保里面的滚动有效 */
    }

    .meeting-list {
      flex: 1;
      overflow-y: auto;
      margin-bottom: 90px;
    }

    .meeting-info {
      display: flex;

      .title {
        width: 60px;
        text-align: center;
        margin-right: 10px;
        margin-top: 20px;
        box-sizing: border-box;
      }

      .meeting {
        flex: 1;

        .meeting-item {
          background-color: #f8f8f8;
          border-radius: 10px;
          padding: 15px;
          margin-bottom: 15px;

          .participant {
            padding: 0;
          }
        }
      }
    }

    .startApp-box {
      background-color: #ffffff;
      width: 100%;
      position: fixed;
      bottom: 0;
      left: 0;
      padding: 20px;
      box-sizing: border-box;
      z-index: 999;
      display: flex;
      gap: 10px;

      .btn {
        flex: 1;
        height: 50px;
        font-size: 18px;
      }
    }

    /* 预约会议按钮 */
    .btn {
      flex: 1;
      height: 50px;
      font-size: 16px;
    }

    .action-box {
      margin-top: 10px; // 增加按钮与上方内容的间距
      display: flex;
      justify-content: flex-start; // 按钮左对齐
      flex-wrap: wrap;
      gap: 10px;
    }

    .meeting-item {
      margin-bottom: 15px; // 增加会议项的底部间距
      padding: 10px;
      background-color: #f8f8f8;
      border-radius: 10px;
    }

    .name-box {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .name {
        font-weight: bold;
        flex: 1;
      }

      .status {
        font-weight: bold;
      }
    }

    .date,
    .promoter,
    .participant {
      color: #6c676b;
      font-size: 13px;
      margin-bottom: 5px;
    }
  }

  .date-selector {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    a-button {
      margin-right: 10px;
    }

    span {
      margin: 0 10px;
      font-size: 16px;
      font-weight: bold;
    }

    a-icon {
      cursor: pointer;
    }
  }

  .invite-container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    width: 100%;
    /* 确保整个组件不会超出 */
  }

  .selected-users {
    display: flex;
    flex-wrap: wrap;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    /* ✅ 每行最多 4 个 */
    gap: 10px;
    width: 100%;
    max-width: 100%;
    /* ✅ 限制最大宽度，避免超出 */
    overflow-x: hidden;
    /* ✅ 禁止横向滚动 */
    margin-top: 1rem;
  }

  .user-card {
    display: flex;
    align-items: center;
    background: #f8f8f8;
    padding: 8px;
    border-radius: 4px;
    position: relative;
    width: calc(50% - 10px);
    margin-left: 20px;
    width: 90px;
    /* 确保两列显示 */
  }

  .user-avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 8px;
  }

  .user-name {
    font-size: 14px;
    font-weight: bold;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  /* X 按钮 */
  .delete-btn {
    position: absolute;
    top: 4px;
    right: 4px;
    background: red;
    color: white;
    border-radius: 50%;
    width: 18px;
    height: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.2s;
  }

  /* 鼠标悬停时显示 X */
  .user-card:hover .delete-btn {
    opacity: 1;
  }

  .room-status {
    max-height: 400px;
    overflow-y: auto;
  }

  .room-status table {
    width: 100%;
    border-collapse: collapse;
  }

  .room-status th,
  .room-status td {
    border: 1px solid #ddd;
    padding: 8px;
  }

  .timeline {
    height: 500px;
    width: 100%;
    overflow-y: auto;
  }

  .timeline-header {
    display: flex;
    width: 100%;
    margin-bottom: 20px;
    /* 增加与下方内容的间距 */
  }

  .hour-label {
    flex: 1 0 calc(100% / 24);
    /* 调整为24份以确保宽度固定 */
    text-align: center;
    font-weight: bold;
    padding: 10px 0;
    border-right: 1px solid #ddd;
    box-sizing: border-box;
    font-size: 14px;
  }

  .timeline-container {
    margin-bottom: 40px;
  }

  .room-info {
    font-weight: bold;
    margin-bottom: 10px;
  }

  .timeline-bar {
    display: flex;
    height: 80px;
    border: 1px solid #ddd;
  }

  .occupancy-slot {
    flex: 1 0 calc(100% / 96);
    /* 确保每小时有4个格子 */
    height: 80px;
    border: 1px solid #ccc;
    box-sizing: border-box;
  }

  a-form {
    max-width: 100%;
    padding: 10px;
    box-sizing: border-box;

    .ant-form-item {
      margin-bottom: 20px;
    }
  }

  /* 针对移动端输入框和选择器的调整 */
  a-input,
  a-select,
  a-date-picker,
  a-input-number {
    width: 100%;
    /* 让所有输入相关元素宽度自适应 */
    font-size: 16px;
    /* 增大字体以提高可读性 */
  }

  a-checkbox,
  a-button {
    margin-top: 10px;
  }
  </style>
